import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Select, InputNumber, Collapse, Space, Tooltip } from 'antd';
import { SearchOutlined, SettingOutlined, ClearOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Panel } = Collapse;

const MethodFilterBar: React.FC<{ onSearch: (values: any) => void }> = ({ onSearch }) => {
    const [form] = Form.useForm();
    const [advancedVisible, setAdvancedVisible] = useState(false);
    const [searchKeyword, setSearchKeyword] = useState('');

    // 通用搜索处理
    const handleQuickSearch = (keyword: string) => {
        setSearchKeyword(keyword);
        
        if (!keyword.trim()) {
            onSearch({});
            return;
        }
        
        // 将关键词同时应用到包名、类名、方法名
        const searchParams = {
            packageName: keyword.trim(),
            className: keyword.trim(),
            methodName: keyword.trim(),
            _isQuickSearch: true // 标记为快速搜索
        };
        
        onSearch(searchParams);
    };

    // 高级搜索处理
    const handleAdvancedSearch = (values: any) => {
        // 过滤掉空值
        const filteredValues = Object.keys(values).reduce((acc, key) => {
            if (values[key] !== undefined && values[key] !== null && values[key] !== '') {
                acc[key] = values[key];
            }
            return acc;
        }, {} as any);
        
        onSearch(filteredValues);
    };

    // 清除所有搜索条件
    const handleClearAll = () => {
        setSearchKeyword('');
        form.resetFields();
        onSearch({});
    };

    // 联动逻辑：服务类型和是否入口
    const handleServiceTypeChange = (value: string) => {
        if (value) {
            // 根据服务类型自动设置是否入口
            const isEntryMap = {
                'DUBBO入口': 'true',
                'REST入口': 'true',
                'REDIS入口': 'true',
                'XXL-JOB入口': 'true',
                'HTTP入口': 'true',
                'NONE': 'false'
            };
            
            const isEntry = isEntryMap[value as keyof typeof isEntryMap];
            if (isEntry !== undefined) {
                form.setFieldsValue({ isEntry });
            }
        }
    };

    const handleIsEntryChange = (value: string) => {
        if (value === 'false') {
            // 如果选择非入口，自动设置服务类型为空
            form.setFieldsValue({ serviceType: undefined });
        }
    };

    return (
        <div style={{ 
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', 
            padding: '24px', 
            borderRadius: '12px', 
            marginBottom: '24px',
            boxShadow: '0 8px 32px rgba(102, 126, 234, 0.15)'
        }}>
            {/* 主搜索区域 */}
            <div style={{ marginBottom: 20 }}>
                <div style={{ 
                    background: '#fff', 
                    borderRadius: '8px', 
                    padding: '16px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                }}>
                    {/* 搜索框和常用筛选 */}
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'flex-end', flexWrap: 'wrap' }}>
                        {/* 通用搜索框 */}
                        <div style={{ flex: 1, minWidth: '300px' }}>
                            <label style={{ 
                                display: 'block', 
                                marginBottom: '6px', 
                                fontSize: '14px', 
                                fontWeight: '500',
                                color: '#333'
                            }}>
                                🔍 通用搜索
                            </label>
                            <Input
                                size="large"
                                placeholder="输入关键词搜索包名、类名或方法名..."
                                value={searchKeyword}
                                onChange={(e) => setSearchKeyword(e.target.value)}
                                onPressEnter={() => handleQuickSearch(searchKeyword)}
                                prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
                                allowClear
                                onClear={() => handleQuickSearch('')}
                                style={{ borderRadius: '6px' }}
                            />
                        </div>

                        {/* 服务类型 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                marginBottom: '6px', 
                                fontSize: '14px', 
                                fontWeight: '500',
                                color: '#333'
                            }}>
                                🏷️ 服务类型
                            </label>
                            <Select 
                                size="large"
                                style={{ width: 140 }} 
                                allowClear 
                                placeholder="选择类型"
                                onChange={handleServiceTypeChange}
                                value={form.getFieldValue('serviceType')}
                            >
                                <Option value="DUBBO入口">DUBBO</Option>
                                <Option value="REST入口">REST</Option>
                                <Option value="REDIS入口">REDIS</Option>
                                <Option value="XXL-JOB入口">XXL-JOB</Option>
                                <Option value="HTTP入口">HTTP</Option>
                            </Select>
                        </div>

                        {/* 是否入口 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                marginBottom: '6px', 
                                fontSize: '14px', 
                                fontWeight: '500',
                                color: '#333'
                            }}>
                                🚪 是否入口
                            </label>
                            <Select 
                                size="large"
                                style={{ width: 100 }} 
                                allowClear
                                onChange={handleIsEntryChange}
                                placeholder="选择"
                                value={form.getFieldValue('isEntry')}
                            >
                                <Option value="true">是</Option>
                                <Option value="false">否</Option>
                            </Select>
                        </div>

                        {/* 快速排序 */}
                        <div>
                            <label style={{ 
                                display: 'block', 
                                marginBottom: '6px', 
                                fontSize: '14px', 
                                fontWeight: '500',
                                color: '#333'
                            }}>
                                🔄 快速排序
                            </label>
                            <Select 
                                size="large"
                                style={{ width: 180 }} 
                                allowClear 
                                placeholder="选择排序方式"
                                onChange={(value) => {
                                    if (value) {
                                        const [orderBy, orderByType] = value.split('_');
                                        form.setFieldsValue({ orderBy, orderByType });
                                    } else {
                                        form.setFieldsValue({ orderBy: undefined, orderByType: undefined });
                                    }
                                }}
                            >
                                <Option value="noCodeChangeDurationDays_desc">📅 修改时间 ↓</Option>
                                <Option value="noCodeChangeDurationDays_asc">📅 修改时间 ↑</Option>
                                <Option value="gitCreateTime_desc">⏰ 创建时间 ↓</Option>
                                <Option value="gitCreateTime_asc">⏰ 创建时间 ↑</Option>
                                <Option value="noSaCallDurationDays_desc">📞 调用时间 ↓</Option>
                                <Option value="noSaCallDurationDays_asc">📞 调用时间 ↑</Option>
                            </Select>
                        </div>

                        {/* 搜索按钮 */}
                        <div>
                            <Button 
                                type="primary" 
                                size="large"
                                onClick={() => {
                                    const serviceType = form.getFieldValue('serviceType');
                                    const isEntry = form.getFieldValue('isEntry');
                                    const orderBy = form.getFieldValue('orderBy');
                                    const orderByType = form.getFieldValue('orderByType');
                                    
                                    const baseParams = {
                                        ...(serviceType && { serviceType }),
                                        ...(isEntry && { isEntry }),
                                        ...(orderBy && { orderBy }),
                                        ...(orderByType && { orderByType })
                                    };
                                    
                                    if (searchKeyword.trim()) {
                                        // 通用搜索 + 筛选条件
                                        const searchParams = {
                                            packageName: searchKeyword.trim(),
                                            className: searchKeyword.trim(),
                                            methodName: searchKeyword.trim(),
                                            _isQuickSearch: true,
                                            ...baseParams
                                        };
                                        onSearch(searchParams);
                                    } else if (Object.keys(baseParams).length > 0) {
                                        // 仅筛选/排序条件
                                        onSearch(baseParams);
                                    } else {
                                        // 无条件搜索
                                        onSearch({});
                                    }
                                }}
                                icon={<SearchOutlined />}
                                style={{ 
                                    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                    border: 'none',
                                    borderRadius: '6px',
                                    height: '40px',
                                    paddingLeft: '24px',
                                    paddingRight: '24px'
                                }}
                            >
                                搜索
                            </Button>
                        </div>
                    </div>
                </div>
                
                {/* 操作按钮区 */}
                <div style={{ 
                    marginTop: 12, 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center' 
                }}>
                    <Button
                        type="text"
                        size="small"
                        icon={<SettingOutlined />}
                        onClick={() => setAdvancedVisible(!advancedVisible)}
                        style={{ 
                            color: '#fff',
                            fontWeight: '500'
                        }}
                    >
                        {advancedVisible ? '收起高级查询' : '展开高级查询'}
                    </Button>
                    
                    <Button
                        type="text"
                        size="small"
                        icon={<ClearOutlined />}
                        onClick={handleClearAll}
                        style={{ 
                            color: '#fff',
                            fontWeight: '500'
                        }}
                    >
                        清除所有条件
                    </Button>
                </div>
            </div>

            {/* 高级查询面板 */}
            {advancedVisible && (
                <div style={{ 
                    background: 'rgba(255, 255, 255, 0.95)', 
                    padding: '20px', 
                    borderRadius: '8px',
                    backdropFilter: 'blur(10px)',
                    border: '1px solid rgba(255, 255, 255, 0.2)',
                    boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
                }}>
                    <div style={{
                        fontSize: '16px',
                        fontWeight: '600',
                        color: '#333',
                        marginBottom: '16px',
                        display: 'flex',
                        alignItems: 'center'
                    }}>
                        ⚙️ 高级查询条件
                    </div>
                    
                    <Form 
                        layout="inline" 
                        form={form} 
                        onFinish={handleAdvancedSearch}
                        style={{ gap: '12px' }}
                    >
                        {/* 隐藏的排序字段 */}
                        <Form.Item name="orderBy" style={{ display: 'none' }}>
                            <Input />
                        </Form.Item>
                        <Form.Item name="orderByType" style={{ display: 'none' }}>
                            <Input />
                        </Form.Item>
                        {/* 精确字段查询 */}
                        <div style={{ width: '100%', marginBottom: '16px' }}>
                            <div style={{ 
                                fontSize: '14px', 
                                fontWeight: '500', 
                                color: '#666', 
                                marginBottom: '8px' 
                            }}>
                                📍 精确字段查询
                            </div>
                            <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                                <Form.Item name="packageName" label="包名">
                                    <Input 
                                        placeholder="精确包名查询" 
                                        allowClear 
                                        style={{ width: 200 }}
                                    />
                                </Form.Item>
                                
                                <Form.Item name="className" label="类名">
                                    <Input 
                                        placeholder="精确类名查询" 
                                        allowClear 
                                        style={{ width: 200 }}
                                    />
                                </Form.Item>
                                
                                <Form.Item name="methodName" label="方法名">
                                    <Input 
                                        placeholder="精确方法名查询" 
                                        allowClear 
                                        style={{ width: 200 }}
                                    />
                                </Form.Item>
                                
                                <Form.Item name="serviceName" label="服务名">
                                    <Input 
                                        placeholder="服务名查询" 
                                        allowClear 
                                        style={{ width: 220 }}
                                    />
                                </Form.Item>
                            </div>
                        </div>

                        {/* 时间范围查询 */}
                        <div style={{ width: '100%', marginBottom: '16px' }}>
                            <div style={{ 
                                fontSize: '14px', 
                                fontWeight: '500', 
                                color: '#666', 
                                marginBottom: '8px' 
                            }}>
                                ⏱️ 时间范围查询
                            </div>
                            <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                                <Form.Item name="noSaCallDurationDays" label="累计无调用时长">
                                    <Tooltip title="查找累计无调用时长大于等于指定天数的方法">
                                        <InputNumber 
                                            min={0} 
                                            placeholder="天数" 
                                            style={{ width: 120 }}
                                            addonAfter="天"
                                        />
                                    </Tooltip>
                                </Form.Item>
                                
                                <Form.Item name="noCodeChangeDurationDays" label="累计无修改时长">
                                    <Tooltip title="查找累计无修改时长大于等于指定天数的方法">
                                        <InputNumber 
                                            min={0} 
                                            placeholder="天数" 
                                            style={{ width: 120 }}
                                            addonAfter="天"
                                        />
                                    </Tooltip>
                                </Form.Item>
                            </div>
                        </div>
                        
                        {/* 操作按钮 */}
                        <div style={{ width: '100%', textAlign: 'center' }}>
                            <Space size="middle">
                                <Button 
                                    type="primary" 
                                    htmlType="submit" 
                                    icon={<SearchOutlined />}
                                    size="large"
                                    style={{
                                        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                        border: 'none',
                                        borderRadius: '6px',
                                        paddingLeft: '24px',
                                        paddingRight: '24px'
                                    }}
                                >
                                    执行高级查询
                                </Button>
                                <Button 
                                    htmlType="button" 
                                    onClick={() => form.resetFields()}
                                    icon={<ClearOutlined />}
                                    size="large"
                                    style={{
                                        borderRadius: '6px',
                                        paddingLeft: '20px',
                                        paddingRight: '20px'
                                    }}
                                >
                                    重置条件
                                </Button>
                            </Space>
                        </div>
                    </Form>
                </div>
            )}
        </div>
    );
};

export default MethodFilterBar; 